const _ = require('lodash')

export function compare<T>(from: T[], to: T[]): {
  _insert: T[],
  _delete: T[]
} {
  const _delete = from.slice()
  const _insert = []

  for (let i = to.length - 1; i >= 0; i -= 1) {
    const idx = from.indexOf(to[i])

    if (idx === -1) {
      _insert.unshift(to[i])
    } else {
      _delete.splice(idx, 1)
    }
  }

  return {
    _insert,
    _delete
  }
}

export function compareObject<T>(from: T[], to: T[], pk = 'id'): {
  _insert: T[],
  _update: T[],
  _delete: T[]
} {
  const _insert = []
  const _update = []
  const _delete = _.keyBy(from, pk)

  for (let i = 0; i < to.length; i += 1) {
    const prop = to[i]

    if (prop[pk]) {
      if (!_.isEqual(_delete[prop[pk]], prop)) {
        _update.push(prop)
      }
      delete _delete[prop[pk]]
    } else {
      _insert.push(prop)
    }
  }

  return {
    _insert,
    _update,
    _delete: _.values(_delete)
  }
}
